//根据一棵树的中序遍历与后序遍历构造二叉树。 
//
// 注意: 
//你可以假设树中没有重复的元素。 
//
// 例如，给出 
//
// 中序遍历 inorder = [9,3,15,20,7]
//后序遍历 postorder = [9,15,7,20,3] 
//
// 返回如下的二叉树： 
//
//     3
//   / \
//  9  20
//    /  \
//   15   7
// 
// Related Topics 树 数组 哈希表 分治 二叉树 
// 👍 529 👎 0


//leetcode submit region begin(Prohibit modification and deletion)
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        TreeNode node = buildRoot(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1);
        return node;
    }

    private TreeNode buildRoot(int[] inorder, int l1, int r1, int[] postorder, int l2, int r2) {

        if (l1 < 0 || r1 >= inorder.length || l2 < 0 || r2 >= postorder.length || l1 > r1 || l2 > r2) {
            return null;
        }
        TreeNode node = new TreeNode();
        node.val = postorder[r2];

        int inordermiddle = -1;
        for (int i = l1; i <= r1; i++) {
            if (inorder[i] == postorder[r2]) {
                inordermiddle = i;
                break;
            }
        }

        if (inordermiddle > 0) {
            //l2 + inordermiddle - l1 - 1 表示postorder[]中应该属于左子树的值
            node.left = buildRoot(inorder, l1, inordermiddle-1, postorder, l2, l2 + inordermiddle - l1 - 1);
        }
        if (r2 != 0) {
            node.right = buildRoot(inorder, inordermiddle+1, r1, postorder, l2 + inordermiddle - l1, r2-1);
        }
        return node;
    }
}
//leetcode submit region end(Prohibit modification and deletion)
